(function() {
    'use strict';

    angular
        .module('milkbeeApp')
        .controller('GiftDialogController', GiftDialogController);

    GiftDialogController.$inject = ['$timeout', '$scope', '$http','$stateParams', '$uibModalInstance', 'entity', 'Gift'];

    function GiftDialogController ($timeout, $scope,$http, $stateParams, $uibModalInstance, entity, Gift) {
        var vm = this;

        vm.gift = entity;
        vm.clear = clear;
        vm.datePickerOpenStatus = {};
        vm.openCalendar = openCalendar;
        vm.save = save;

        $timeout(function (){
            angular.element('.form-group:eq(1)>input').focus();
        });

        function clear () {
            $uibModalInstance.dismiss('cancel');
        }

        function save () {
        	 vm.isSaving = true;
             if (vm.gift.id !== null) {
                 Gift.update(vm.gift, onSaveSuccess, onSaveError);
             } else {
            	 Gift.save(vm.gift, onSaveSuccess, onSaveError);
             }
        }

        function onSaveSuccess (result) {
            $scope.$emit('milkbeeApp:giftUpdate', result);
            $uibModalInstance.close(result);
            vm.isSaving = false;
        }

        function onSaveError () {
            vm.isSaving = false;
        }

        vm.datePickerOpenStatus.createdAt = false;

        function openCalendar (date) {
            vm.datePickerOpenStatus[date] = true;
        }
        
        
        vm.onPictureSelect=function($files){
        	for (var i = 0; i < $files.length; i++) {        		
        		var fd = new FormData();
        		//Take the first selected file
        		fd.append("jyfile", $files[i]);     	      
        		$http({
        			method: 'post',
        			url: '/upload/gift',
        			data:fd,
        			headers: {'Content-Type': undefined},
        			transformRequest: angular.identity
        		}).success(function(ret) {
        			if (ret.success) {
        				vm.gift.picture=ret.path;
        			}else if(!ret.success){
        			}
        		})
        		//only one file
        		break;
        	}
        }
    }
})();
